import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Dispatch } from 'redux'
import type { RootState } from '@/types/store'
import { useMemoizedFn } from 'ahooks'
/**
 * 进入页面获取相应数据
 * @param action 获取数据的action函数
 * @param stateName 获取状态的名称，对应RootState中某个状态的名称
 * @returns 要获取的状态
 */
export const useInitialState = <StateName extends keyof RootState>(
  action: () => void,
  stateName: StateName,
  afterAction = () => {}
): RootState[StateName] => {
  const dispatch = useDispatch<Dispatch<any>>()
  const state = useSelector<RootState, RootState[StateName]>(
    (state) => state[stateName]
  )
  // const actionRef = useRef(action)
  // const afterActionRef = useRef(afterAction)
  const memoizedAction = useMemoizedFn(action)
  const memoizedAfterAction = useMemoizedFn(afterAction)

  useEffect(() => {
    const loadData = async () => {
      await dispatch(memoizedAction())

      memoizedAfterAction()
    }
    loadData()
  }, [dispatch, memoizedAction, memoizedAfterAction])

  return state
}
